# audio_processor.py
import pyaudio
import wave
import os
from config.config import Config


class AudioRecorder:
    """音频录制处理类"""

    def __init__(self, config):
        self.config = config
        self.p = pyaudio.PyAudio()
        self.wake_word_duration = 3  # 唤醒词检测时长（秒）

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.p.terminate()

    def record(self, filename):
        """录制音频"""
        stream = self.p.open(
            format=self.config.AUDIO_FORMAT,
            channels=self.config.CHANNELS,
            rate=self.config.SAMPLE_RATE,
            input=True,
            frames_per_buffer=self.config.CHUNK_SIZE
        )

       #  print("\n录音中...（{}秒）".format(self.config.RECORD_DURATION))
        frames = [
            stream.read(self.config.CHUNK_SIZE)
            for _ in range(0, int(self.config.SAMPLE_RATE / self.config.CHUNK_SIZE * self.config.RECORD_DURATION))
        ]
        print("录音结束")

        stream.stop_stream()
        stream.close()

        self._save_wav(frames, filename)
        return filename

    def listen_for_wake_word(self, filename="wake_word.wav"):
        """持续监听唤醒词"""
        stream = self.p.open(
            format=self.config.AUDIO_FORMAT,
            channels=self.config.CHANNELS,
            rate=self.config.SAMPLE_RATE,
            input=True,
            frames_per_buffer=self.config.CHUNK_SIZE
        )

        frames = []
        frame_count = int(self.config.SAMPLE_RATE / self.config.CHUNK_SIZE * self.wake_word_duration)
        
        for _ in range(frame_count):
            data = stream.read(self.config.CHUNK_SIZE)
            frames.append(data)

        stream.stop_stream()
        stream.close()

        self._save_wav(frames, filename)
        return filename

    def _save_wav(self, frames, filename):
        """保存为WAV文件"""
        with wave.open(filename, 'wb') as wf:
            wf.setnchannels(self.config.CHANNELS)
            wf.setsampwidth(self.p.get_sample_size(self.config.AUDIO_FORMAT))
            wf.setframerate(self.config.SAMPLE_RATE)
            wf.writeframes(b''.join(frames))